package com.loop.niochat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * NIO 群聊服务端
 * @author zhangxiaolu
 * @since 2023-09-05 22:23
 */
public class GroupChatServer {

    // 定义属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int port = 6667;

    // 构造器，初始化工作
    public GroupChatServer() {
        try {
            // 得到选择器
            selector = Selector.open();
            // 得到通道listenChannel
            listenChannel = ServerSocketChannel.open();
            // 绑定端口
            listenChannel.socket().bind(new InetSocketAddress(port));
            // 设置非阻塞
            listenChannel.configureBlocking(false);
            // 把通道注册到选择器
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 监听
    public void listen() {
        try {
            while (true) {
                // 阻塞等待2s
                int count = selector.select();
                if (count > 0) {// 有事件处理
                    // 遍历得到selectionKey 集合
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    // 遍历事件
                    while (iterator.hasNext()) {
                        // 获取事件
                        SelectionKey key = iterator.next();
                        // 处理事件 监听到accept
                        if (key.isAcceptable()) {
                            SocketChannel sc = listenChannel.accept();
                            // 设置非阻塞
                            sc.configureBlocking(false);
                            // 将该sc注册到selector
                            sc.register(selector, SelectionKey.OP_READ);
                            // 提示
                            System.out.println(sc.getRemoteAddress() + " 上线");
                        }
                        // 处理事件 监听到read
                        if (key.isReadable()) {
                            // 处理读的方法
                            readData(key);
                        }
                        // 删除事件，避免重复处理
                        iterator.remove();
                    }
                }/* else
                    System.out.println("等待2s");*/
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 读取客户端消息
    private void readData(SelectionKey key) {
        // 定义一个SocketChannel
        SocketChannel channel = null;
        try {
            // 获取一个SocketChannel
            channel = (SocketChannel) key.channel();
            // 创建一个Buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            // 读取数据到buffer
            int read = channel.read(buffer);
            // 如果没有读取到内容，返回
            if (read > 0) {
                // 读取到内容，进行显示
                String msg = new String(buffer.array());
                System.out.println("客户端发送的消息：" + msg);
                // 向其他客户端转发消息
                sendInfoToOtherClients(msg, channel);
            }
        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + " 离线");
                key.cancel(); // 取消注册
                channel.close(); // 关闭通道
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }

    // 发送消息给其他客户端，排除自己
    private void sendInfoToOtherClients(String msg, SocketChannel self) throws IOException {
        System.out.println("服务器转发消息中。。。");
        // 遍历集合中的SocketChannel
        for (SelectionKey key : selector.keys()) {
            // 通过key 取出对应的SocketChannel
            Channel targetChannel = key.channel();
            // 排除自己
            if (targetChannel instanceof SocketChannel && targetChannel != self) {
                // 获取SocketChannel
                SocketChannel dest = (SocketChannel) targetChannel;
                // 写入数据到buffer
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                // 发送数据
                dest.write(buffer);
            }
        }
    }

    public static void main(String[] args) {
        // 创建服务器对象
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }
}
